//
//  CHJAlertView.m
//  JiPin
//
//  Created by HaiJiao Chen on 11-9-15.
//  Copyright 2011年 Kaixin. All rights reserved.
//

#import "CHJAlertView.h"
#import "AppDelegate.h"
#import <QuartzCore/QuartzCore.h>

@implementation CHJAlertView
@synthesize timer;

-(id)init
{
    UIWindow* window = [AppDelegate sharedInstance].window;
    CGRect frame = window.frame;
    self = [super initWithFrame:frame];
    if (self)
    {
        self.bounds = window.bounds;
        self.windowLevel = UIWindowLevelAlert;
        self.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.4];
        self.transform = window.transform;
        
		UIImage *background = [[UIImage imageNamed:@"loadingbg.png"] stretchableImageWithLeftCapWidth:6 topCapHeight:6];
		backgroundView = [[UIImageView alloc] initWithImage:background];
        backgroundView.layer.cornerRadius = 10;
        backgroundView.layer.masksToBounds = YES;
        [self addSubview:backgroundView];
        
        contentView = [[UIView alloc] initWithFrame:CGRectZero];
		contentView.backgroundColor = [UIColor clearColor];
        contentView.clipsToBounds = YES;
        [self addSubview:contentView];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientation) name:@"deviceOrientation" object:nil];
    }
    return self;
}
 
#define ZOOM_OFFSET_WIDTH 120
-(void)showAnimation
{
    /*CGRect allRect = contentView.bounds;
    self.alpha = 0.2;
    // Draw rounded HUD bacgroud rect
    CGRect boxRect = CGRectMake(0,
                                0,
                                allRect.size.width + ZOOM_OFFSET_WIDTH,
                                allRect.size.height + ZOOM_OFFSET_WIDTH);
    
    backgroundView.layer.cornerRadius = boxRect.size.width / 15;
    backgroundView.bounds = boxRect;
    backgroundView.center = contentView.center;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.30];
    self.alpha = 1.0;
    backgroundView.bounds = allRect;
     [UIView commitAnimations];*/
    CGRect allRect = contentView.bounds; 
    // Draw rounded HUD bacgroud rect
    CGRect boxRect = CGRectMake(0,
                                0,
                                allRect.size.width + ZOOM_OFFSET_WIDTH,
                                allRect.size.height + ZOOM_OFFSET_WIDTH);
    
    backgroundView.layer.cornerRadius = 5;//boxRect.size.width / 15;
    backgroundView.bounds = boxRect;
    backgroundView.center = contentView.center;
    
    backgroundView.bounds = allRect;
    contentView.alpha = 0.2;
    backgroundView.alpha =  0.2;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.50];
    backgroundView.alpha = 1.0;
    contentView.alpha = 1.0;
    [UIView commitAnimations];
}

-(void)setTitle:(NSString*)title max_width:(NSInteger)max_width animated:(BOOL)animated
{
    NSArray* subs = [contentView subviews];
    for (UIView *view in subs)
    {
        [view removeFromSuperview];
    }
    
    UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font =[UIFont systemFontOfSize:15];
    titleLabel.textAlignment = UITextAlignmentCenter;
    titleLabel.numberOfLines = 1;
    titleLabel.adjustsFontSizeToFitWidth =YES;
    titleLabel.minimumFontSize = 14;
    titleLabel.frame = CGRectMake(20, 20, max_width, 56);
    titleLabel.text = title? title:@"";
    [titleLabel sizeToFit];
    [contentView addSubview:titleLabel];
    [titleLabel release];

    CGRect rc = self.bounds;
    CGRect rc_title = titleLabel.frame;
    rc.size = CGSizeMake( rc_title.size.width+40, rc_title.size.height+40);
    contentView.center = CGPointMake(self.frame.size.height/2, self.frame.size.width/2.0);
    contentView.bounds = rc;
    //int x = rc.origin.x + (rc.size.width - rc_title.size.width-40)/2;
    //int y = rc.origin.y + (rc.size.height - rc_title.size.height-40)/2;  
    //contentView.frame = CGRectMake(x, y, rc_title.size.width+40, rc_title.size.height+40); 
    
    if (animated)
	{
		[self showAnimation];
	}
    else
    {
        backgroundView.frame = contentView.frame;
    }
}

#define MARGIN 20.0
#define PADDING 20.0
#define LABELFONTSIZE 15.0
#define INDICATORY 14.0
#define INDICATORWIDTH 20.0
-(void)setLoadingText:(NSString*)text animated:(BOOL)animated
{
    self.userInteractionEnabled = YES;
    NSArray* subs = [contentView subviews];
    for (UIView *view in subs)
    {
        [view removeFromSuperview];
    }
    
    
    UIActivityIndicatorView* indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    
    [indicator startAnimating];
    [contentView addSubview:indicator];
    [indicator release];
    
    //计算contentView的大小
    UILabel *label = [[UILabel alloc] initWithFrame:self.bounds];
    const int magic = 71;
    CGSize content = CGSizeMake(96, magic);
    if (nil != text) {
        CGSize size = self.frame.size;
        UIFont* labelFont = [UIFont boldSystemFontOfSize:LABELFONTSIZE];
        // Get size of label text
        CGSize dims = [text sizeWithFont:labelFont];
        
        // Compute label dimensions based on font metrics if size is larger than max then clip the label width
        float lHeight = dims.height;
        float lWidth;
        if (dims.width <= (size.width - 2 * MARGIN - INDICATORWIDTH - 5)) {
            lWidth = dims.width;
        }
        else {
            lWidth = size.width - 4 * MARGIN;
        }
        
        // Update HUD size
        if (content.width < (lWidth + 2 * MARGIN + INDICATORWIDTH + 5)) {
            content.width = lWidth + 2 * MARGIN + INDICATORWIDTH + 5;
        }
        
        if ( content.height < lHeight + PADDING + MARGIN) {
            content.height = lHeight + PADDING + MARGIN;
        } 
    
        // Set label properties
        label.font = labelFont;
        label.adjustsFontSizeToFitWidth = NO;
        label.textAlignment = UITextAlignmentCenter;
        label.opaque = NO;
        label.backgroundColor = [UIColor clearColor];
        label.textColor = [UIColor whiteColor];
        label.text = text;
        label.frame = CGRectMake(0, 0, lWidth, lHeight);
        [contentView addSubview:label];
    }
        
    CGRect rc = self.bounds;
    rc.size = content;
    contentView.center = CGPointMake(self.frame.size.height/2, self.frame.size.width/2.0);
    contentView.bounds = rc;
    
    indicator.center = CGPointMake(MARGIN + INDICATORWIDTH/2, contentView.frame.size.height/2);
    label.center = CGPointMake(MARGIN + INDICATORWIDTH + 5 + label.frame.size.width / 2, indicator.center.y);

    [label release];
	if (animated)
	{
		[self showAnimation];
	}
    else
    {
        backgroundView.frame = contentView.frame;
    }
}

-(void)deviceOrientation
{
    UIWindow* window = [AppDelegate sharedInstance].window;
    self.bounds = window.bounds;
    self.transform = window.transform;
    CGRect rc = self.bounds;
    CGRect rc_content = contentView.frame;
    int x = rc.origin.x + (rc.size.width - rc_content.size.width)/2;
    int y = rc.origin.y + (rc.size.height - rc_content.size.height)/2;
    contentView.frame = CGRectMake(x, y, rc_content.size.width, rc_content.size.height);
    backgroundView.frame = contentView.frame;
}

-(void)dealloc
{
    [contentView release];
    if ([timer isValid])
    {
        [timer invalidate];
    }
    [timer release];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

-(void)show
{
    if ([self isHidden])
    {
        [self setHidden:NO];
        [self retain];
        if (show == NO)
        {
            show = YES;
        }
    }
}

-(void)setHidden:(BOOL)hidden
{
    [super setHidden:hidden];
    [[AppDelegate sharedInstance].window makeKeyAndVisible];
}
-(void)close
{
    //[NSObject cancelPrevioussPerformRequestsWithTarget:self selector:@selector(close) object:nil];
    [self.timer invalidate];
    if (![self isHidden])
    {
        if (show == YES)
        {
            show = NO;
        }
        [self setHidden:YES];
        [self release];
    }
}

-(void)closeInTime:(NSTimeInterval)time
{
    self.userInteractionEnabled = NO;
//    [self performSelector:@selector(close) withObject:nil afterDelay:time];
    NSInvocation *timerFireInvocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(close)]];
    [timerFireInvocation setTarget:self];
    [timerFireInvocation setSelector:@selector(close)];
    self.timer = [NSTimer timerWithTimeInterval:time invocation:timerFireInvocation repeats:YES];
    
    NSRunLoop *runner = [NSRunLoop currentRunLoop];
    [runner addTimer: self.timer forMode:  NSRunLoopCommonModes];
    if (show == YES)
    {
        show = NO;
    }
}

@end
